package com.wutao.panzh.index.content.Filter;

import com.panzh.entity.index.UserInfo;
import com.panzh.myconst.UserContst;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 此类为一个登录的一个过滤器类，防止非正常的后台访问。这里的*,代表模糊匹配哈.
 * uriPatterns后面一定要跟一个“/”在写个*。才能起到模糊匹配的功能；
 */
@WebFilter(filterName = "sessionFilter",urlPatterns = {"/user/admin/*"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        System.out.println("filter被创建了！");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
//        System.out.println("已经进入过滤器内部！！");
        //取出userInfo对象；
        UserInfo info = (UserInfo)session.getAttribute(UserContst.USER_INFO_IS_EXIST);
//        System.out.println(info);
        if (info == null){
            //这里没有进行登录，我们直接进行一个重定向，重定向到页面的首页。
            response.sendRedirect(request.getContextPath()+"/index");
            return;
        }
        //放入request域进行随时调用；
        request.setAttribute(UserContst.USER_INFO,info);
        //进行放行处理
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
